package com.lims.landInfo.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javacommon.base.*;
import javacommon.util.TextTool;

import cn.org.rapid_framework.page.*;

import com.lims.landInfo.model.*;
import com.lims.landInfo.dao.*;
import com.lims.landInfo.vo.query.*;

/**
 * @author zzh
 * @version 1.0
 * @since 1.0
 */@Service
@Transactional @SuppressWarnings("unchecked")
public class ProjectManager extends BaseManager<Project,java.lang.String>{

	private ProjectDao projectDao;
	/**增加setXXXX()方法,spring就可以通过autowire自动设置对象属性,请注意大小写*/
	public void setProjectDao(ProjectDao dao) {
		this.projectDao = dao;
	}
	public EntityDao getEntityDao() {
		return this.projectDao;
	}
	
	@Transactional(readOnly=true)
	public Page findPage(ProjectQuery query) {
		return projectDao.findPage(query);
	}
	
	@Transactional(readOnly=true)
	public ListRange findRange(ProjectQuery query) {
		Page page = this.projectDao.findPage(query);
		ListRange listRange = new ListRange();
		listRange.setRows(page.getResult().toArray());
		listRange.setTotal(page.getTotalCount());
		return listRange;
	}
	/**
	 * 验证并保存数据
	 * @return
	 */
	public List saveAndCheckImpData(Collection entities,Date landDate) {
		List errList = new ArrayList(0);
		Date curDate = new Date(System.currentTimeMillis());
		for (Iterator iterator = entities.iterator(); iterator.hasNext();) {
			Project project = (Project) iterator.next();
			project.setCreateDate(curDate);
			project.setLandDate(landDate);
			String errMsg = checkLand(project);
			if(TextTool.isNotNull(errMsg)) {
				project.setDescribe(errMsg);
				errList.add(project);
			} else {
				this.projectDao.save(project);
			}
		}
		return errList; 
	}
	
	/**
	 * 验证
	 * 返回若为空，验证通过，若不为空，返回验证失败原因
	 * @return
	 */
	private String checkLand(Project project) {
		String msg = "";
		if(TextTool.isNull(project.getLandno())) {
			msg += "宗地编号为空。";
		} else{
			String hql = "from Project l where l.landno=?";
			List landList = this.projectDao.find(hql, project.getLandno());
			if(TextTool.isNotNull(landList)) {
				String oldYear = project.getLandDateString().substring(0, 4);
				String newYear = ((Project)landList.get(0)).getLandDateString().substring(0,4);
				if(oldYear.equals(newYear)) {
					msg += "宗地编号重复。";
				}
			}
		}
		return msg;
	}
	
}
